<script setup lang="ts">
/**
 * @author lwlianghehe@gmail.com
 * @date 2024/11/22
 */
import kanbanTemplate from "./kanban-template.tsx";
import {ComponentInternalInstance, getCurrentInstance, inject, ref, watch} from "vue";
import {LocationQueryValue, useRoute} from "vue-router";
import {addModelApi, createModelApi, getModelAllApi, getModelPageApi, invokeMethod} from "../../../../api/modelApi.ts";
import ActionView from "../../../../model/view/ActionView.ts";
import {getTemplate, XMLParserResult} from "../../../../xml/XMLParserResult.ts";
import {parserEx} from "../../../../xml/XMLParser.ts";
import {refreshPage} from "../../../../util/commonUtils.ts";
import {useFieldStore} from "../../../../global/store/fieldStore.ts";
import {useServiceStore} from "../../../../global/store/serviceStore.ts";
import {getActionFormView, getActionKanbanView} from "../../../../api/commonApi.ts";
import MySearch from "../../../../components/search/my-search.vue";
import {getPageSize} from "../../../../api/env.ts";
import {ButtonClickEvent} from "../../../../model/ButtonClickEvent.ts";
import ServiceInvokeParam from "../../../../model/ServiceInvokeParam.ts";
import { getModelKeyValue } from "../../../../util/fieldUtils.ts";
import ViewAction from "../../../../components/view-action/view-action.vue";
import MyFormModel from "../../../../components/model/form-dialog/my-form-dialog.vue";
import mittBus from "../../../../global/bus/mittBus.ts";



const route = useRoute();
const serviceFieldStore = useFieldStore()
const serviceStore = useServiceStore()
const rowClickHandler = inject('rowClick') as (id: number | undefined) => void;

const moduleName = ref<string>(route.params.module as string)
const serviceName = ref<string>(route.params.service as string)

// 加载状态管理
const isLoading = ref<boolean>(true)
const isDataLoading = ref<boolean>(false)

const view = ref<ActionView | undefined>(undefined)
getActionKanbanView(serviceName.value).then(data => {
  if (data && data.length) {
    view.value = data[0]
    renderView();
  }
  isLoading.value = false
})

const rowTargetShow = ref(false)
const rowTargetTitle = ref('')
const rowTargetId = ref()
const selectRow = ref()


const createServiceClick = async () => {
  const formView = await getActionFormView(serviceName.value)
    if (formView && formView.length && formView[0].target == 'new') { // 弹出Form窗口
      rowTargetShow.value = true
      rowTargetId.value = undefined
      const defaultValue = await createModelApi({}, serviceName.value)
      const serviceKeyField = await serviceStore.getServiceByNameAsync(serviceName.value)
      if (serviceKeyField && serviceKeyField.keyField) {
        defaultValue[serviceKeyField.keyField] = getModelKeyValue()
      }
      rowTargetTitle.value = formView[0].label
      selectRow.value = defaultValue
    } else {
      rowClickHandler(undefined)
    }
}

const subRowSureClick = (row: any) => {
  rowTargetShow.value = false
  if (selectRow.value) {
    Object.assign(selectRow.value, row)
  } 
  
  addModelApi(selectRow.value, serviceName.value).then(data => {
    loadData()
  })
}

const subRowCloseClick = () => {
  rowTargetShow.value = false
}

const xmlTemplate = ref<any>(null)

const renderView = () => {
  if (view.value) {
    parserXml(view.value.arch)
  }
}

let template_fields = ref<string[]>([]);

let parserResult: XMLParserResult | null = null;

const parserXml = async (str: string) => {
  parserResult = await parserEx(str, serviceName.value)
  xmlTemplate.value = getTemplate(parserResult)
  template_fields.value.splice(0, template_fields.value.length)
  template_fields.value.push(...parserResult.fullFields.map(field => field.name))
}


const {proxy} = getCurrentInstance() as ComponentInternalInstance;


const record = ref<any>([])
const pageNum = ref<number>(1)
const condition = ref<string>('')
const begin = ref<number>(0)
const end = ref<number>(0)
const total = ref<number>(0)
const loadData = () => {
  if (!(moduleName.value && serviceName.value && template_fields.value.length)) {
    return;
  }
  isDataLoading.value = true
  getModelPageApi(template_fields.value.join(","),
      condition.value, serviceName.value, pageNum.value).then(pageInfo => {
    if (pageInfo.data) {
      record.value.splice(0, record.value.length);
      record.value.push(...pageInfo.data)
    }
    begin.value = (pageInfo.pageCur - 1) * getPageSize() + 1
    end.value = begin.value + pageInfo.data.length - 1
    total.value = pageInfo.total
    isDataLoading.value = false
  }).catch(() => {
    isDataLoading.value = false
  })
}

watch(() => [moduleName.value, serviceName.value, template_fields.value.length], ([v1, v2, v3]) => {
  if (v1 && v2 && v3) {
    loadData()
  }
}, {
  immediate: true
})


const btnClick = (arg: ButtonClickEvent, fields: any) => {
  const param = {
    serviceName: serviceName.value,
    method: arg.action,
    param: fields
  }
  if (serviceName.value) {
    invokeMethod(serviceName.value, param as ServiceInvokeParam).then(data => {
      proxy?.$notify.success({
        title: "提示",
        message: "操作成功",
      });
      setTimeout(() => {
        refreshPage()
      }, 1000)
    })
  }
}
const conditionChange = (search: string) => {
  condition.value = search;
  pageNum.value = 1
  loadData();
}
const handlePageChange = (dir: string) => {
  if (dir == 'right') { // 下一页
    pageNum.value = pageNum.value + 1;
  } else {
    pageNum.value = pageNum.value - 1;
  }
  loadData()
}

const navigateToView = (viewMode: string) => {
  console.log("navigateToView",viewMode)
  if(viewMode == 'kanban'){
    return
  }
  mittBus.emit('changeViewMode', {viewMode: viewMode})
}

const goModelFormClick = (item: any) => {
  rowClickHandler(item.id)
}
</script>

<template>
  <div class="h-full p-4 overflow-hidden flex flex-col box-border">
    <div class="w-full">
      <div class="h-[50px] flex items-start w-full px-4">
        <div class="flex-1 h-[34px]">
          <el-button-group>
            <el-button type="primary" size="small" @click="createServiceClick">新增</el-button>

          </el-button-group>
      </div>
        <div class="flex-1">
          <MySearch @conditionChange="conditionChange" :full-width="true" class="w-full"
                    :serviceName="serviceName"/>
        </div>
        <div class="flex-1 flex justify-end gap-2 h-[34px] items-center">
          <MyPagination v-model:total="total" v-model:begin="begin" v-model:end="end"
                        @pageChange="handlePageChange"></MyPagination>
          <ViewAction :service="serviceName" @select="navigateToView" active="kanban"></ViewAction>
        </div>
      </div>
    </div>
    <el-scrollbar class="w-full h-full box-border" >
      <!-- 骨架屏加载状态 -->
      <div v-if="isLoading || isDataLoading" class="p-4">
        <el-row :gutter="16">
          <el-col :span="6" v-for="i in 8" :key="i" :xs="24" :sm="12" :md="8" :lg="6">
            <div class="w-[96%] mb-4">
              <el-skeleton :rows="4" animated>
                <template #template>
                  <div class="p-4 border rounded-lg shadow-sm">
                    <el-skeleton-item variant="h3" style="width: 60%; height: 20px; margin-bottom: 16px;" />
                    <el-skeleton-item variant="text" style="width: 100%; height: 16px; margin-bottom: 8px;" />
                    <el-skeleton-item variant="text" style="width: 80%; height: 16px; margin-bottom: 8px;" />
                    <el-skeleton-item variant="text" style="width: 90%; height: 16px; margin-bottom: 16px;" />
                    <div class="flex justify-between items-center">
                      <el-skeleton-item variant="button" style="width: 60px; height: 32px;" />
                      <el-skeleton-item variant="button" style="width: 40px; height: 32px;" />
                    </div>
                  </div>
                </template>
              </el-skeleton>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 空数据显示 -->
      <div v-else-if="!isLoading && !isDataLoading && record.length === 0" class="flex flex-col items-center justify-center h-full py-16 empty-state">
        <div class="text-center">
          <div class="mb-4">
            <svg class="mx-auto h-16 w-16 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">暂无数据</h3>
          <p class="text-sm text-gray-500 mb-6">当前没有找到任何记录，您可以点击"新增"按钮来创建第一条记录</p>
          <el-button type="primary" @click="createServiceClick" class="px-6">
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            新增记录
          </el-button>
        </div>
      </div>
      
      <!-- 有数据时显示看板 -->
      <el-row v-else-if="!isLoading && !isDataLoading && record.length > 0">
        <el-col :span="6" v-for="item in record" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6">
          <div class="w-[96%] mb-4">
            <kanbanTemplate @click="goModelFormClick(item)" v-if="xmlTemplate" :template="xmlTemplate" :fields="item"
            @btnClick="btnClick"></kanbanTemplate>
          </div>
        </el-col>
      </el-row>
    </el-scrollbar>

    
  <MyFormModel v-if="rowTargetShow" v-model="rowTargetShow"
                 :title="rowTargetTitle"
                 :service="serviceName"
                 :row-id="rowTargetId"
                 :old-record-row="selectRow"
                 @close="subRowCloseClick"
                 @sure="subRowSureClick"></MyFormModel>
  </div>
</template>

<style scoped>
/* 空状态样式 */
.empty-state {
  min-height: 400px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px;
  border: 1px dashed #cbd5e1;
}

.empty-state:hover {
  border-color: #94a3b8;
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
}

/* 空状态图标动画 */
.empty-state svg {
  transition: all 0.3s ease;
}

.empty-state:hover svg {
  transform: scale(1.05);
  color: #64748b;
}

/* 按钮悬停效果 */
.empty-state .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>